import ArticleItem from '@/components/ArticleItem';
import { useAppSelector } from '@/store';
import { getArtilesByIdAction, updateArtilesByIdAction } from '@/store/action/articles';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useDispatch } from 'react-redux';
/*
  学习目标：滚动加载的数据，存入redux中
  步骤：
     1. 定义actionType
     2. dipatch触发aciton
     3. 编写计算逻辑
*/

export default function ArticleList() {
  const { currentId } = useAppSelector((state) => state.channel);
  const { articleList } = useAppSelector((state) => state.article);
  const list = articleList[currentId]?.results || [];
  const dispatch = useDispatch();
  // 1. 取出后台返回的时间戳
  const pre_timestamp = articleList[currentId]?.pre_timestamp;
  const loadMore = async () => {
    // 使用新的时间戳，请求数据
    await dispatch(updateArtilesByIdAction({ channel_id: currentId, timestamp: pre_timestamp }));
  };

  // 下拉刷新
  const handleRefresh = async () => {
    await dispatch(getArtilesByIdAction({ channel_id: currentId }));
  };
  return (
    <div>
      <PullToRefresh onRefresh={handleRefresh}>
        {list.map((item) => {
          return <ArticleItem itemData={item as any} key={item.art_id} />;
        })}
      </PullToRefresh>
      {/* 💥下方控制数据为空时，不去显示无限滚动组件 */}
      {!!list.length && <InfiniteScroll loadMore={loadMore} hasMore={!!pre_timestamp} />}
    </div>
  );
}
